//
//  QNJsbridge.m
//  JSAPIModule
//
//  Created by sumeng on 2018/3/2.
//

#define QN_jsbridgeWeakSelf __weak typeof(self) weakSelf = self;
#import "QNJsbridge.h"

@implementation QNJsbridge
@synthesize bridge = _bridge;

#pragma mark 设置webView对象
- (void)setWebView:(WKWebView *)webView {
    _webView = webView;
    [self initJsbridge];
}

#pragma mark 初始化Jsbridge对象
- (void)initJsbridge {
    _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView];
    [self registerHandler];
}

#pragma mark  注册公共方法
- (void)registerHandler {
    
}

#pragma mark 注册回调
- (void)registerHandler:(NSString *)handler responseBlock:(QN_responseBlock)responseBlock{
    QN_jsbridgeWeakSelf
    [_bridge registerHandler:handler handler:^(id data, WVJBResponseCallback responseCallback) {
        [weakSelf logWithHandler:handler data:data];
        NSDictionary* params = data;
        responseBlock(params);
        responseCallback([weakSelf responseCallWithHandler:handler]);
    }];
}
#pragma mark 发送消息
- (void)callHandler:(NSString *)handler data:(id)data responseBlock:(QN_responseBlock)responseBlock{
    QN_jsbridgeWeakSelf
    [_bridge callHandler:handler data:data responseCallback:^(id responseData) {
        [weakSelf logWithHandler:handler data:data];
        responseBlock(responseData);
    }];
}
#pragma mark 打印日志
- (void)logWithHandler:(NSString *)handler data:(id)data {
    if (self.logging) {
        NSLog(@"%@ called: %@",handler,data);
    }
}

#pragma mark 拼接回调信息
- (NSString *)responseCallWithHandler:(NSString *)handler {
    return [NSString stringWithFormat:@"%@ success",handler];
}
@end
